<template>
  <div class="ques-bank-container layout-padding">
    <el-card class="left menu-data-tree">
      <CateTree @onCateClick="handlerNodeClick" dicType="QUES_CATE"></CateTree>

    </el-card>
    <el-card shadow="hover" class="layout-padding-auto right">
      <el-row class="mb20">
        <el-form inline>
          <el-form-item>
            <el-input  clearable placeholder="请输入标题"
                      v-model="state.tableData.param.quesInfo"></el-input>
          </el-form-item>
          <el-form-item>
            <el-select
         
                clearable
                @clear="handleOnQuesLevelChange"
                v-model="state.tableData.param.quesLevel"
                class="m-2"
                placeholder="请选择试题难度"
                @change="handleOnQuesLevelChange"
            >
              <el-option :key="1" label="简单" :value="1"/>
              <el-option :key="2" label="普通" :value="2"/>
              <el-option :key="3" label="困难" :value="3"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button   @click="getTableData" type="primary">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-dropdown @command="handleCommand">
              <el-button type="primary"  >
                添加试题
                <el-icon class="el-icon--right">
                  <ele-ArrowDown/>
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="1">单选题</el-dropdown-item>
                  <el-dropdown-item :command="2">多选题</el-dropdown-item>
                  <el-dropdown-item :command="3">判断题</el-dropdown-item>
                  <el-dropdown-item :command="4">填空题</el-dropdown-item>
                  <!-- <el-dropdown-item :command="5">问答题</el-dropdown-item> -->
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-form-item>
          <el-form-item>
            <el-button   @click="onImportQues" type="primary">导入</el-button>
          </el-form-item>
          <el-form-item>
            <el-button  @click="onExportQues" type="primary">导出</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <el-table class="table" :data="state.tableData.data" stripe style="width: 100%"
                v-loading="state.tableData.loading">
        <el-table-column prop="id" label="id"/>
        <el-table-column prop="quesInfo" label="题干"/>
        <el-table-column prop="cateName" label="分类名称" show-overflow-tooltip/>
        <el-table-column prop="quesLevel" label="难度" show-overflow-tooltip>
          <template #default="scope">
            <el-tag v-if="scope.row.quesLevel === 1">简单</el-tag>
            <el-tag v-else-if="scope.row.quesLevel === 2">普通</el-tag>
            <el-tag v-else-if="scope.row.quesLevel === 3">困难</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quesType" label="题型" show-overflow-tooltip>
          <template #default="scope">
            <el-tag v-if="scope.row.quesType === 1">单选题</el-tag>
            <el-tag v-else-if="scope.row.quesType === 2">多选题</el-tag>
            <el-tag v-else-if="scope.row.quesType === 3">判断题</el-tag>
            <el-tag v-else-if="scope.row.quesType === 4">填空题</el-tag>
            <el-tag v-else-if="scope.row.quesType === 5">简答题</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip/>
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="onTableEditRow(scope.row)">编辑</el-button>
            <el-button link type="primary" size="small" @click="onTableDelRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="onHandleSizeChange"
          @current-change="onHandleCurrentChange"
          class="mt15"
          :page-sizes="[10, 20, 30]"
          v-model:current-page="state.tableData.param.pageNum"
          background
          v-model:page-size="state.tableData.param.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.tableData.total"
      >
      </el-pagination>
    </el-card>

    <QuesBankDialog ref="quesBankDialogRef" @refresh="getTableData"></QuesBankDialog>
    <QuesImportDialog ref="quesImportDialogRef" @refresh="getTableData"></QuesImportDialog>
  </div>
</template>

<script setup name="makeTableDemo">
import {defineAsyncComponent, onMounted, reactive, ref, watch} from 'vue';
import {useQuesApi} from '/@/api/ques';
import {ElMessage, ElMessageBox} from 'element-plus';

// 引入组件
const QuesBankDialog = defineAsyncComponent(() => import('/@/views/ques/bank/dialog.vue'));
const QuesImportDialog = defineAsyncComponent(() => import('/@/views/ques/bank/importDialog.vue'));
const CateTree = defineAsyncComponent(() => import('/@/components/cate/index.vue'))


const quesApi = useQuesApi();

const quesBankDialogRef = ref();
const quesImportDialogRef = ref();


// 定义变量内容
const state = reactive({
  tableData: {
    cateData: [], // 分类
    // 列表数据（必传）
    data: [],
    // 表头内容（必传，注意格式）
    total: 0,
    loading: false,
    // 搜索参数（不用传，用于分页、搜索时传给后台的值，`getTableData` 中使用）
    param: {
      pageNum: 1,
      pageSize: 10,
      quesLevel: '',
      quesType: '',
      quesInfo: '',
      cateId: '',
    },
  },
});


// 分页改变
const onHandleSizeChange = (val) => {
  state.tableData.param.pageSize = val;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val) => {
  state.tableData.param.pageNum = val;
  getTableData();
};


// 分类点击
const handlerNodeClick = (id) => {
  state.tableData.param.cateId = id
  getTableData()
}



// 初始化列表数据
const getTableData = () => {
  state.tableData.loading = true;
  state.tableData.data = [];
  quesApi
      .bankPage({
        page: state.tableData.param.pageNum,
        limit: state.tableData.param.pageSize,
        search: {
          quesInfo: state.tableData.param.quesInfo,
          quesLevel: state.tableData.param.quesLevel,
          quesType: state.tableData.param.quesType,
          cateId: state.tableData.param.cateId,
        }
      })
      .then((res) => {
        state.tableData.data = res.data.list;
        state.tableData.total = res.data.count;
        state.tableData.loading = false;
      });
};

// 删除当前项回调
const onTableDelRow = (row) => {
  ElMessageBox.confirm(`您确认要删除吗，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        quesApi.bankDelete({ids: [row.id]}).then(() => {
          ElMessage.success(`删除${row.quesInfo}成功！`);
          getTableData();
        });
      })
      .catch(() => {
      });
};

//编辑当前行
const onTableEditRow = (row) => {
  quesBankDialogRef.value.openDialog('edit', row);
};

const onImportQues = () => {
  quesImportDialogRef.value.openDialog();
};

const onExportQues = () => {
  quesApi.exportQues({
    search: {
      quesInfo: state.tableData.param.quesInfo,
      quesLevel: state.tableData.param.quesLevel,
      quesType: state.tableData.param.quesType,
      cateId: state.tableData.param.cateId,
    }
  }).then(res => {
    const {data, headers, request} = res;

    // 此处当返回json文件时需要先对data进行JSON.stringify处理，其他类型文件不用做处理
    const blob = new Blob([data], {type: headers['content-type']});
    const dom = document.createElement('a');
    const downUrl = window.URL.createObjectURL(blob);
    dom.href = downUrl;
    dom.download = decodeURIComponent('导出的试题.xlsx');
    dom.style.display = 'none';
    document.body.appendChild(dom);
    dom.click();
    dom.parentNode?.removeChild(dom);
    window.URL.revokeObjectURL(request.responseURL);
    window.URL.revokeObjectURL(downUrl);
  })
};

// 新增
const handleCommand = (command) => {
  quesBankDialogRef.value.openDialog('add', {
    quesType: command,
  });
};
//
// // 分类点击
// const handlerCateChange = (id: string) => {
//     state.tableData.param.cateId = id;
// };

const handleOnQuesLevelChange = (level) => {
  state.tableData.param.quesLevel = level;
};


// 页面加载时
onMounted(() => {
  getTableData();
});
</script>

<style scoped lang="scss">
.ques-bank-container {
  display: flex;
  flex-direction: row;

  .left {
    padding-top: 20px;
    min-width: 260px;
    margin-right: 20px;
    overflow: auto;
  }

  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;

    .el-table {
      flex: 1;
    }
  }
}
</style>
